package mdr.demo

import org.apache.commons.lang.StringUtils

class InstanceService {

	boolean transactional = false
	String instanceclassname // MUST be initialized by the subclass
	def domainclass
	def grailsApplication

	// TODO: setup() in the services need to be called before the service is used. Maybe put the calls in Bootstrap
	public void setup() {
	//    domainclass = grailsApplication.getDomainClass(instanceclassname)    // doesn't work
	//    domainclass = grailsApplication.getDomainClass(instanceclassname).clazz
	    domainclass = grailsApplication.getClassForName(instanceclassname)    // works
	    println "domainclass $instanceclassname"
	}
	
	public def getCount() {
	     def count = domainclass.count()
	    //grailsApplication.getDomainClass('SomeClass').newInstance()
	     return count
	}
	
	public def getById(String id) {
		if (id) {
			domainclass.get(id?.toLong())
		}
	}
	
	public def getById(Long id) {
		if (id) {
			domainclass.get(id)
		}
	}
	
	public def list(Map params) {
		domainclass.list(params);
	}
	
	public def delete(Object instance) {
		instance.delete()
	}
	
	public def update(Object instance) {
		instance.save()
	}
	
	public def newInstance() {
		domainclass.newInstance()
	}
	
	public def save(Map params) {
		println("...>> $params")
		def obj = newInstance()
		obj.properties = params
		obj.save()
//		println("obj is null? ($obj == null)")
		return obj
	}
/*	
	public def isUsed(Object instance) {
		def obj = newinstance()
		obj.properties = params
		obj.save()
	}
*/	
}